package com.zw.yzk.kabu.data.repository;


import com.zw.yzk.kabu.data.network.entity.Entity;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.cache.store.UserStore;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.service.ModifyUserInfoService;
import com.zw.yzk.kabu.data.network.task.ModifyUserInfoTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2016/12/24.
 */

public class ModifyUserInfoRepository extends CommonRepository {

    @Inject
    UserStore userStore;
    private ModifyUserInfoTask userInfoTask;

    @Inject
    public ModifyUserInfoRepository() {

    }

    @Override
    protected Observable connectServer(Task task) {
        ModifyUserInfoService service = ServiceGenerator.createService(ModifyUserInfoService.class);
        userInfoTask = (ModifyUserInfoTask) task;

        return service.modifyUserInfo(userInfoTask);
    }

    @Override
    protected Func1<Entity, Observable> getServerData() {
        return new Func1<Entity, Observable>() {
            @Override
            public Observable call(Entity entity) {
                if (entity.errCode == Constant.RESULT_OK) {
                    updateUserInfo();
                }
                return Observable.just(entity.errCode == Constant.RESULT_OK);
            }
        };
    }

    //更新数据库个人信息
    private void updateUserInfo() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null) {
            return;
        }
        user.setSex(userInfoTask.sex);
        if (userInfoTask.nickName != null) {
            user.setNickName(userInfoTask.nickName);
        }
        if (userInfoTask.province != null) {
            user.setProvince(userInfoTask.province);
        }
        if (userInfoTask.city != null) {
            user.setCity(userInfoTask.city);
        }
        if(userInfoTask.sign != null) {
            user.setIntroduction(userInfoTask.sign);
        }
        if (userInfoTask.head != null) {
            user.setHeadUrl(userInfoTask.head);
        }
        if (userInfoTask.homePage != null) {
            user.setHomePage(userInfoTask.homePage);
        }
        userStore.updateUserInfo(user);
    }
}
